import markdown
from markdown.extensions import fenced_code
# from markdown.extensions import footnotes
from markdown.extensions import attr_list
from markdown.extensions import def_list
from markdown.extensions import tables
from markdown.extensions import abbr
from markdown.extensions import md_in_html

from aqt.qt import QMimeData, QImage
from anki import hooks
from anki.template import TemplateRenderContext

import datetime
import requests
import tempfile
import os

# ===== Markdown
def on_editor_will_munge_html(txt, editor):
  editor.web.eval(f"myaddonRefreshEditor()")
  
  return markdown.markdown(txt, extensions=[
    fenced_code.makeExtension(),
    # footnotes.makeExtension(),
    attr_list.makeExtension(),
    def_list.makeExtension(),
    tables.makeExtension(),
    abbr.makeExtension(),
    md_in_html.makeExtension(),
  ])

# ===== Paste
def on_editor_will_process_mime(mime: QMimeData, editor_web_view, internal, extended, drop_event):
  ret = mime

  if internal:
    pass
  
  elif mime.hasImage():
    fd, tempfilename = tempfile.mkstemp()

    try:
      image = QImage(mime.imageData())
      filesize = image.sizeInBytes()

      image.save(tempfilename, 'PNG')
      with open(tempfilename, 'rb') as img_file:
        obj_name = f'anki_img_{str(int(datetime.datetime.now().timestamp()))}.png'
        r = requests.post('http://192.168.0.150:7070/minio', files={'file': (tempfilename, img_file, 'image/png')}, params={'filesize': filesize, 'bucket': 'appdata', 'path': f'anki/{obj_name}'}, headers={'Authorization': 'Basic 1f5e53699261fd3dd39fa3cb85fab4d4'})
        r.raise_for_status()
        result = r.json()

      myData = QMimeData()
      myData.setText(f'![](https://image.mhugh.net/appdata/anki/{obj_name})')
      ret = myData
    except Exception as e:
      pass
    finally:
      os.close(fd)
      os.remove(tempfilename)

  return ret

# # filter
# # called each time a custom filter is encountered
# def my_field_filter(
#   field_text: str,
#   field_name: str,
#   filter_name: str,
#   context: TemplateRenderContext,
# ) -> str:
#   if not filter_name.startswith("info-"):
#     # not our filter, return string unchanged
#     return field_text

#   # split the name into the 'info' prefix, and the rest
#   try:
#     (label, rest) = filter_name.split("-", maxsplit=1)
#   except ValueError:
#     return invalid_name(filter_name)

#   # call the appropriate function
#   if rest == "card-interval":
#     return card_interval(context)
#   elif rest == "note-creation":
#     return note_creation(context)
#   else:
#     return invalid_name(filter_name)

# def invalid_name(filter_name: str) -> str:
#   return f"invalid filter name: {filter_name}"

# def card_interval(ctx: TemplateRenderContext) -> str:
#   return str(ctx.card().ivl)

# def note_creation(ctx: TemplateRenderContext) -> str:
#   # convert millisecond timestamp to seconds
#   note_creation_unix_timestamp = ctx.note().id // 1000
#   # convert timestamp to a human years-months-days
#   return time.strftime("%Y-%m-%d", time.localtime(note_creation_unix_timestamp))

def setup_editor():
  from aqt.gui_hooks import editor_will_munge_html, editor_will_process_mime
  # markdown
  editor_will_munge_html.append(on_editor_will_munge_html)
  # media
  editor_will_process_mime.append(on_editor_will_process_mime)
  # # register our function to be called when the hook fires
  # hooks.field_filter.append(my_field_filter)